package com.mdx.rest.service;

import com.mdx.api.entity.CommunityUser;
import com.mdx.rest.repository.RoleRepository;
import com.mdx.rest.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 配置自定义的userDetailsService来进行验证
 * @author : jiagang
 * @date : Created in 2022/2/8 16:44
 */
@Service
public class MyUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    @Autowired
    private UserRepository userRepository;


    @Autowired
    private RoleRepository roleRepository;

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        // 查询用户
        CommunityUser user = userRepository.findByUserName(login);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        // 设置角色
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        // 查询角色
//        List<MdxRole> userRole = roleRepository.findRoleAllByUserId(user.getUserId());
//        if (StringUtils.isEmpty(userRole)){
//            throw new BusinessException("用户无角色");
//        }
        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN"); // 暂时写死
        // 设置角色
        grantedAuthorities.add(simpleGrantedAuthority);

        return new User(login,user.getPassword(), true, true, true, true,grantedAuthorities);
    }
}
